// 引入工具类
const { articleApi } = require('../../../utils/api')
const { formatTime } = require('../../../utils/dateUtils')
const { favoritesStore, newsStore } = require('../../../utils/store')

Page({
  data: {
    newsId: '',
    newsDetail: {},
    loading: true,
    isFavorited: false,
    relatedNews: []
  },

  onLoad(options) {
    console.log('新闻详情页面加载，参数:', options)
    if (options.id) {
      this.setData({ newsId: options.id })
      this.fetchNewsDetail(options.id)
    } else {
      wx.showToast({
        title: '缺少文章ID',
        icon: 'error'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  onShow() {
    console.log('新闻详情页面显示')
    // 检查收藏状态
    this.checkFavoriteStatus()
  },

  // 获取新闻详情
  async fetchNewsDetail(newsId) {
    try {
      this.setData({ loading: true })

      const response = await articleApi.getArticleDetail(newsId)
      console.log('新闻详情API响应:', response)

      // 处理不同的响应格式
      let articleData = null
      if (response && response.data) {
        articleData = response.data
      } else if (response && response.news_id) {
        // 直接返回文章数据的情况
        articleData = response
      } else if (response && response.code === 200 && response.data) {
        articleData = response.data
      }

      if (articleData) {
        const newsDetail = {
          newsId: articleData.news_id || articleData.newsId || newsId,
          title: articleData.title || '无标题',
          content: articleData.content_html || articleData.contentHtml || '',
          contentText: articleData.content_text || articleData.contentText || '',
          category: articleData.category || '',
          section: articleData.section || '',
          pubTime: articleData.pub_time || articleData.pubTime,
          formattedTime: formatTime(articleData.pub_time || articleData.pubTime),
          author: articleData.author || '系统管理员',
          processedContent: this.processHtmlContent(articleData.content_html || articleData.contentHtml || '')
        }

        this.setData({
          newsDetail,
          loading: false
        })

        // 添加到浏览历史
        const app = getApp()
        app.addHistory(newsDetail)

        // 检查收藏状态
        this.checkFavoriteStatus()

        // 获取相关新闻
        this.fetchRelatedNews()

      } else {
        throw new Error('获取新闻详情失败')
      }

    } catch (error) {
      console.error('获取新闻详情失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  // 处理HTML内容 - 使用简化的HTML字符串处理
  processHtmlContent(htmlContent) {
    if (!htmlContent) {
      return ''
    }

    // 临时使用简化的HTML处理，直接返回HTML字符串给rich-text组件
    try {
      // 预处理HTML内容
      let processedContent = htmlContent

      // 处理图片路径
      processedContent = processedContent.replace(
        /src="\/([^"]+)"/g,
        'src="https://college.guducat.cn/$1"'
      )

      // 移除一些不支持的标签和属性
      processedContent = processedContent.replace(/<script[^>]*>.*?<\/script>/gi, '')
      processedContent = processedContent.replace(/<style[^>]*>.*?<\/style>/gi, '')

      // 为图片添加响应式样式
      processedContent = processedContent.replace(
        /<img([^>]*)>/gi,
        '<img$1 style="max-width: 100%; height: auto; display: block; margin: 12px auto; border-radius: 8px;">'
      )

      // 为段落添加样式
      processedContent = processedContent.replace(
        /<p([^>]*)>/gi,
        '<p$1 style="margin: 12px 0; text-align: justify; line-height: 1.6; font-size: 16px;">'
      )

      // 为标题添加样式
      processedContent = processedContent.replace(
        /<(h[1-6])([^>]*)>/gi,
        '<$1$2 style="margin: 16px 0 8px 0; font-weight: 600; line-height: 1.4;">'
      )

      return processedContent

    } catch (error) {
      console.error('HTML处理失败，使用降级处理:', error)

      // 降级处理：返回纯文本
      const textContent = htmlContent
        .replace(/<[^>]*>/g, '')
        .replace(/&nbsp;/g, ' ')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .trim()

      return textContent
    }
  },

  // 检查收藏状态
  checkFavoriteStatus() {
    const isFavorited = favoritesStore.isFavorited(this.data.newsId)
    this.setData({ isFavorited })
  },

  // 切换收藏状态
  toggleFavorite() {
    const newsDetail = this.data.newsDetail
    if (!newsDetail.newsId) {
      wx.showToast({
        title: '文章信息不完整',
        icon: 'error'
      })
      return
    }

    const isFavorited = favoritesStore.toggleFavorite(newsDetail)
    this.setData({ isFavorited })

    wx.showToast({
      title: isFavorited ? '已添加到收藏' : '已取消收藏',
      icon: 'success'
    })
  },

  // 分享新闻
  shareNews() {
    const newsDetail = this.data.newsDetail
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

    // 可以在这里添加分享统计
    console.log('分享新闻:', newsDetail.title)
  },

  // 获取相关新闻
  async fetchRelatedNews() {
    try {
      // 根据分类获取相关新闻
      const category = this.data.newsDetail.category
      if (!category) return

      const response = await articleApi.getArticlesByCategory(category, 1, 5)
      if (response && response.data) {
        const rawList = response.data.records || response.data.list || response.data || []

        // 过滤掉当前文章
        const relatedNews = rawList
          .filter(item => (item.news_id || item.newsId || item.id) != this.data.newsId)
          .slice(0, 3)
          .map(item => ({
            newsId: item.news_id || item.newsId || item.id,
            title: item.title,
            formattedTime: formatTime(item.pub_time || item.pubTime)
          }))

        this.setData({ relatedNews })
      }
    } catch (error) {
      console.error('获取相关新闻失败:', error)
      // 相关新闻获取失败不影响主要功能
    }
  },

  // 跳转到相关新闻
  goToRelatedNews(event) {
    const newsId = event.currentTarget.dataset.newsId
    if (newsId) {
      wx.redirectTo({
        url: `/pages/news/detail/detail?id=${newsId}`
      })
    }
  },

  // 处理内容点击事件
  handleContentTap(event) {
    console.log('内容点击:', event)
    // 可以在这里处理图片预览等功能
  }
})
